<?php

require_once("TeamSpeak3/TeamSpeak3.php");

class eveonline_ts_config {

  // Teamspeak 3 Server Query Information (REQUIRED)
  public $tshost = "127.0.0.1";
  public $tsname = "serveradmin";
  public $tspass = "FGqIo5xG";
  public $tsport = "10011"; //ServerQuery Port
  public $tscport = "9987"; //TeamSpeak client port

}

function eveonline_settings_teamspeak() {
  $sql = db_query("SELECT * FROM {eveonline_teamspeak}");
  $roles = eveonline_get_roles('select');
  $header = array(t('Drupal ID'), t('Teamspeak ID'));
  $i = 0;
  while ($tsrole = db_fetch_object($sql)) {
    $tablerow[$i]['rid'] = $roles[$tsrole->rid];
    $tablerow[$i]['tsgid'] = $tsrole->tsgid;
    $i++;
  }
  $output = theme('table', $header, $tablerow);
  $output .= drupal_get_form('eveonline_settings_teamspeak_form');
  return $output;
}

function eveonline_settings_teamspeak_form($form_state) {
  $roles = eveonline_get_roles('select');
  $form['ts'] = array(
    '#type' => 'fieldset',
    '#title' => t('Add role'),
    '#collapsible' => FALSE,
    '#collapsed' => FALSE,
  );
  $form['ts']['rid'] = array(
    '#type' => 'select',
    '#title' => t('Role'),
    '#default_value' => isset($edit) ? $edit->rid : 2,
    '#options' => $roles,
    '#description' => t('What role grant to new user.'),
  );
  $form['ts']['tsgid'] = array(
    '#type' => 'textfield',
    '#title' => t('Teamspeak group ID'),
    '#size' => 10,
    '#maxlenght' => 2,
    '#default_value' => isset($edit) ? $edit->tsgid : '',
  );
  $form['ts']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Add'),
  );
  return $form;
}

function eveonline_settings_teamspeak_form_submit($form, &$form_state) {
  $data = (object) $form_state['values'];
  $savedata = array(
    'rid' => $data->rid,
    'tsgid' => $data->tsgid,
  );
  drupal_write_record('eveonline_teamspeak', $savedata);
  drupal_set_message(t('Group added'));
  $form_state['redirect'] = 'admin/settings/eveonline/teamspeak';
}

function eveonline_ts() {
  drupal_set_title(t('TeamSpeak registration'));
  global $user;
  $ts = db_fetch_object(db_query("SELECT tsdbid, tsuid FROM {eveonline_teamspeak_users} WHERE uid = %d", $user->uid));
  $characters = eveonline_get_characters($user->uid);

  $changenick = TRUE;

  $sql = db_query("SELECT * FROM {eveonline_teamspeak}");
  while ($tsrole = db_fetch_object($sql)) {
    foreach ($user->roles as $rid => $rolename) {
      if ($tsrole->rid == $rid) {
        $groups[] = $tsrole->tsgid;
      }
    }
  }

  if (count($characters) > 0) {
    foreach ($characters as $character) {
      $CharacterSheet = eveonline_get_characterSheet($character->userID, $character->apiKey, $character->characterID);
      switch ($CharacterSheet) {
        case 'Login denied by account status.':
          break;
        default:
          $CorporationSheet = eveonline_get_api('corp/CorporationSheet', $character->userID, $character->apiKey, $character->characterID);
          $names[] = '[' . $CorporationSheet->result->ticker . '] ' . $CharacterSheet->result->name;
      }
    }
    foreach ($names as $name) {
      $check = eveonline_ts_checkname($name);
      if ($check) {
        $changenick = FALSE;
        if ($ts->tsuid) {
          if ($ts->tsuid == $check->ts_uniqueID) {
            eveonline_ts_addgroups($name, $groups);
            $output .= 'Your Unique ID: ' . $check->ts_uniqueID;
          }
          else {
            $output .= t('You allready registered in teamspeak server with Unique ID: ') . $ts->tsuid . '</br>';
          }
        }
        else {
          eveonline_ts_addgroups($name, $groups);
          db_query("INSERT INTO {eveonline_teamspeak_users} (uid, tsdbid, tsuid) VALUES ('%d', '%d', '%s')", $user->uid, $check->ts_baseID, $check->ts_uniqueID);
          $output .= 'Your Unique ID: ' . $check->ts_uniqueID;
        }
        continue;
      }
    }
  }
  else {
    $output .= t('You need provide characters at') . l(t('this page'), 'user/' . $user->uid . '/characters') . t(' for access to TeamSpeak');
  }
  if ($changenick) {
    eveonline_ts_kick($ts->tsuid, $names);
    $output .= t('You are not connected to TeamSpeak server or you have invalid nickname. Change your nickname to follow one:</br>');
    foreach ($names as $name) {
      $output .= $name . '</br>';
    }
  }
  return $output;
}

function eveonline_ts_checkname($name) {
  $c = new eveonline_ts_config;
  try {
    $ts3_VirtualServer = TeamSpeak3::factory("serverquery://" . $c->tsname . ":" . $c->tspass . "@" . $c->tshost . ":" . $c->tsport . "/?server_port=" . $c->tscport);
  }
  catch (TeamSpeak3_Exception $e){
    die("An error occured: " . $e->getMessage() . " [F" . __LINE__ . "]");
  }
  try {
    $tsClient = $ts3_VirtualServer->clientGetByName($name);
    $result->ts_baseID = $tsClient->client_database_id;
    $result->ts_uniqueID = $tsClient->client_unique_identifier;
  }
  catch (TeamSpeak3_Exception $e){
    $result = FALSE;
  }
  return $result;
}

function eveonline_ts_addgroups($name, $groups) {
  $c = new eveonline_ts_config;
  try {
    $ts3_VirtualServer = TeamSpeak3::factory("serverquery://" . $c->tsname . ":" . $c->tspass . "@" . $c->tshost . ":" . $c->tsport . "/?server_port=" . $c->tscport);
  }
  catch (TeamSpeak3_Exception $e){
    die("An error occured: " . $e->getMessage() . " [F" . __LINE__ . "]");
  }
  foreach ($groups as $group) {
    try {
      $ts3_VirtualServer->clientGetByName($name)->addServerGroup($group);
    }
    catch (TeamSpeak3_Exception $e){
      
    }
  }
}

function eveonline_ts_kick($tsUniqueID, $names) {
  $c = new eveonline_ts_config;
  $message = 'SecurityBot: Change nickname to ';
  foreach ($names as $name) {
    $message .= $name . ' ';
  }
  try {
    $ts3_VirtualServer = TeamSpeak3::factory("serverquery://" . $c->tsname . ":" . $c->tspass . "@" . $c->tshost . ":" . $c->tsport . "/?server_port=" . $c->tscport);
  }
  catch (TeamSpeak3_Exception $e){
    die("An error occured: " . $e->getMessage() . " [F" . __LINE__ . "]");
  }
  try {
    $ts3_VirtualServer->clientGetByUid($tsUniqueID)->Kick(TeamSpeak3::KICK_SERVER, $message);
  }
  catch (TeamSpeak3_Exception $e){
    
  }
}

?>